package org.leno.houseHire.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.leno.houseHire.action.LoginCondition;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;


public class LoginDAOImpl extends HibernateDaoSupport implements ILoginDAO {
	

	public boolean valid(User user) {
		Session session = this.getSession();
		Query query = session.createQuery("from User u where u.uname=:name and u.upass=:pass");
		query.setString("name", user.getUname());
		query.setString("pass", user.getUpass());
		Object obj = query.uniqueResult();
		session.close();
		if(obj!=null){
			User user2= (User) obj;
			user.setUid(user2.getUid());
			return true;
		}
		return false;
	}

	public void addUser(User user) {
		getHibernateTemplate().save(user);
		
	}

	public int delUser(List<String> ids) {
		List<User> users = new ArrayList<User>();
		for (String id : ids) {
			User user = findById(Integer.parseInt(id));
			users.add(user);
		}
		getHibernateTemplate().deleteAll(users);
		return ids.size();
	}

	public void editUser(User user) {
		getHibernateTemplate().update(user);
		
	}

	public List<User> findAllUser(LoginCondition cond,final int start,final int limit) {
		final String uname = cond.getUname();
		return getHibernateTemplate().executeFind(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Criteria cr = session.createCriteria(User.class).setFirstResult(start).setMaxResults(limit);
				if(uname!=null&&!uname.trim().equals("")){
					cr.add(Restrictions.like("uname", "%" +uname+"%"));
				}
				return cr.list();
			}
		});
	}

	public User findById(int id) {
		return (User) getHibernateTemplate().get(User.class, id);
	}

	public long getTotalNums(LoginCondition cond) {
		final String uname = cond.getUname();
		return (Integer)getHibernateTemplate().execute(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Criteria cr = session.createCriteria(User.class);
				if(uname!=null&&!uname.trim().equals("")){
					cr.add(Restrictions.like("uname", "%" +uname+"%"));
				}
				cr.setProjection(Projections.count("uid"));
				return cr.uniqueResult();
			}
		});
	}

}
